package com.zb.netty.chat.server;

import com.zb.netty.chat.protocal.MessageCodecSharable;
import com.zb.netty.chat.protocal.ProtocolFrameDecoder;
import com.zb.netty.chat.server.handler.RpcRequestMessageHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author: zhaobin
 * @date: 2024/6/25 20:28
 * @Description:
 */
public class RpcServer {
    public static void main(String[] args) {
        // 连接请求处理
        NioEventLoopGroup boss = new NioEventLoopGroup();
        // 读写事件处理
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 日志处理的handler
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        // 消息的编解码器
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        // rpc请求消息处理器
        RpcRequestMessageHandler RPC_REQUEST_HANDLER = new RpcRequestMessageHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_REQUEST_HANDLER);
                }
            });
            Channel channel = serverBootstrap.bind(8089).sync().channel();
            channel.closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}

